/**
 * @file /src/main_window.cpp
 *
 * @brief Implementation for the qt gui.
 *
 * @date February 2011
 **/
/*****************************************************************************
** Includes
*****************************************************************************/

#include <QtGui>
#include <QMessageBox>
#include <iostream>
#include "../include/ui_core/main_window.hpp"
#include <sys/sysinfo.h>
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <QTimer>
/*****************************************************************************
** Namespaces
*****************************************************************************/

namespace ui_core {

using namespace Qt;

/*****************************************************************************
** Implementation [MainWindow]
*****************************************************************************/
#include <QDebug>

#define BATTERY_CMD "upower --dump | grep --color=never -E \"state|to\ full|to\ empty|percentage\" | tail -n 1"
#define WIFI_CMD "iwconfig wlo1 | grep Link | awk -F '[/]' '{print $1F}' | awk -F '[=]' '{print $NF}'"

MainWindow::MainWindow(int argc, char** argv, QWidget *parent)
	: QMainWindow(parent)
	, qnode(argc,argv)
{
	ui.setupUi(this); // Calling this incidentally connects all ui's triggers to on_...() callbacks in this class.
    //QTimer::singleShot(1000, this, SLOT(GetSystemInfo()));
    // set time:
    QTimer *timer = new QTimer(this);
    timer->start(1000); //每隔1000ms发送timeout的信号
    connect(timer, SIGNAL(timeout()),this,SLOT(time_update()));
    connect(timer, SIGNAL(timeout()),this,SLOT(showBattery()));
    connect(timer, SIGNAL(timeout()),this,SLOT(showWifi()));
    // set statusbar:
    //ui.statusbar->addWidget(ui.label_if_track_success);
    // 设置tongji logo
    //QSize sz(370,90);
    //QPixmap pixmapBattery(":images/tongjidaxue.png");
    //pixmapBattery=pixmapBattery.scaled(sz);
    ui.label_tongji->setText("  同济大学---V4R课题组  ");
    //ui.label_tongji->setScaledContents(true);
   // ui.label_tongji->setAlignment(Qt::AlignHCenter); // 贴边

    // 设置图标
    setWindowIcon(QIcon(":/images/icon.jpeg"));
    ui.button_connect->setIcon(QIcon(":/images/con.png"));
    ui.quit_button->setIcon(QIcon(":/images/exit.jpeg"));
    ui.pbt_img->setIcon(QIcon(":/images/sub.jpeg"));
    ui.pbt_img_rect->setIcon(QIcon(":/images/start.jpeg"));
    ui.pbt_cmd->setIcon(QIcon(":/images/runn.png"));
    //
    // 设置tabWidget
    //（1）背景色；
    //（2）选中颜色；
    //（3）字体设置；
    QObject::connect(ui.actionAbout_Qt, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt())); // qApp is a global variable for the application
    connect(&qnode,SIGNAL(image_val(QImage)),this,SLOT(slot_update_image(QImage)));
    connect(&qnode,SIGNAL(tracking_val(int, int, int, int)),this,SLOT(slot_update_rectangle(int, int, int, int)));
    connect(ui.pbt_img,SIGNAL(clicked()),this,SLOT(slot_sub_image()));
    connect(ui.pbt_cmd,SIGNAL(clicked()),this,SLOT(slot_cmd_input()));

    // get system info
    //connect(ui.pbt_start_up,SIGNAL(clicked()),this,SLOT(getSystemInfo()));
    // QTimer::singleShot(500, this, SLOT(getSystemInfo()));

    ReadSettings();

	ui.tab_manager->setCurrentIndex(0); // ensure the first tab is showing - qt-designer should have this already hardwired, but often loses it (settings?).
    QObject::connect(&qnode, SIGNAL(rosShutdown()), this, SLOT(close()));

	/*********************
	** Logging
	**********************/
	ui.view_logging->setModel(qnode.loggingModel());
 // ui.view_logging->setGeometry(200,0,800,150);
    QObject::connect(&qnode, SIGNAL(loggingUpdated()), this, SLOT(updateLoggingView()));

    ItemModel = new QStandardItemModel(this);

    /*********************
    ** Auto Start
    **********************/
    if ( ui.checkbox_remember_settings->isChecked() ) {
        on_button_connect_clicked(true);
    }

}

MainWindow::~MainWindow() {}
// command input by   butters
void MainWindow::slot_cmd_input()
{
    cmd_pro=new QProcess;//初始化QProcess对象
    cmd_pro->start("bash");//启动bash(终端)
    cmd_pro->write(ui.text_input->text().toLocal8Bit()+'\n');//写入要发布的命令
    connect(cmd_pro,SIGNAL(readyReadStandardError()),this,SLOT(slot_cmd_output()));
    connect(cmd_pro,SIGNAL(readyReadStandardOutput()),this,SLOT(slot_cmd_output()));

}

int getBattery(){
    FILE *fp=nullptr;
    fp=popen(BATTERY_CMD,"r");
    char read_str[512]="";
    int res = 0;
    fgets(read_str,sizeof(read_str),fp);
    std::string t = std::string(read_str).substr(25,28);
    res = std::atoi(t.c_str());
    pclose(fp);
    return res;
}

int getWifiStrenth(){
    FILE *fp = nullptr;
    fp = popen(WIFI_CMD,"r");
    int res = 0;
    char read_str[10] = "";
    fgets(read_str, sizeof(read_str), fp);
    res = std::atoi(std::string(read_str).c_str());
    pclose(fp);
    return res;
}

void MainWindow::showBatteryIcon(QString fileName){
    QSize sz(27, 27);
    QPixmap pixmapBattery(fileName);
    pixmapBattery=pixmapBattery.scaled(sz);
    ui.label_battery->setPixmap(pixmapBattery);
}

void MainWindow::showBattery(){
    int remainPower = getBattery();
   // QSize sz(25, 25);
    if(remainPower>=75)
    {
        showBatteryIcon(":/images/battery4.png");
    } else if(remainPower>=50 && remainPower<75){
        showBatteryIcon(":/images/battery3.png");
    }  else if(remainPower>=25 && remainPower<50){
        showBatteryIcon(":/images/battery2.png");
    }  else if(remainPower>=5 && remainPower<25){
        showBatteryIcon(":/images/battery1.png");
    }  else {
        showBatteryIcon(":/images/battery0.png");
    }
    ui.label_battery_precentage->setText(QString::number(remainPower)+"%");
}

void MainWindow::showWifiIcon(QString fileName){
    QSize sz(23, 23);
    QPixmap pixmapWifi(fileName);
    pixmapWifi=pixmapWifi.scaled(sz);
    ui.label_wifi->setPixmap(pixmapWifi);
}

void MainWindow::showWifi(){
    int wifi_strenth = getWifiStrenth();
    if(wifi_strenth >= 68){
        showWifiIcon(":/images/s1.png");
    } else if(wifi_strenth >= 60){
        showWifiIcon(":/images/s2.png");
    } else if(wifi_strenth >= 50){
        showWifiIcon(":/images/s3.png");
    } else{
        showWifiIcon(":/images/s4.png");
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event){
    //坐标
    QPoint viewPoint = event->pos();
    //scenePoint = mapToScene(viewPoint);
    setMouseTracking(true);
    //ui.label_if_track_success->setText("("+QString::number(viewPoint.x())+","+QString::number(viewPoint.y())+")");
    //ui.statusbar->addWidget(ui.label_if_track_success);
}

void MainWindow::time_update()
{
    //获取时间
    QDateTime current_time = QDateTime::currentDateTime();
    QString timestr = current_time.toString( "yyyy年MM月dd日 hh:mm:ss"); //设置显示的格式
    ui.label_current_time->setText(timestr); //设置label的文本内容为时间
}

void MainWindow::getSystemInfo()
{
    /*1. 获取当前系统磁盘使用情况*/
        /*
         * 格式:  /dev/sda1        49G   38G  9.3G   81% /
         */
        QProcess process;
        process.start("bash");
        process.write("head -n 2 /proc/meminfo\n");
        process.waitForFinished();
        QByteArray output = process.readAllStandardOutput();
        QString str_output = output;
        //str_output=str_output.mid(str_output.indexOf("/dev/sda1"));
       // ui.label_track_if_success->setText("1234");
        QTimer::singleShot(500, this, SLOT(getSystemInfo()));
}

void MainWindow::slot_update_image(QImage im)
{
    ui.lab_img->setPixmap(QPixmap::fromImage(im));
}

#include <QString>
#include <QStandardItem>
#include <QTime>

double get_rand_nums(){
    QTime randtime;
    randtime = QTime::currentTime();
    qsrand(randtime.msec()+randtime.second()*1000); //以当前时间ms为随机种子

    int n = qrand() % 100;    //产生100以内的随机整数
    double fn = double(n)/10;   //产生10以内的随机浮点数，精度为小数点后1位
    return fn;
}

void MainWindow::slot_update_rectangle(int x1, int y1, int x2, int y2)
{
    ui.lab_img->x1 = x1;
    ui.lab_img->y1 = y1;
    ui.lab_img->x2 = x2;
    ui.lab_img->y2 = y2;

    QString string = QString("[INFO] Time:") + QString("[") + QString::number(ros::Time::now().toSec()) + QString("]") +" "+ QString("Tracking Success! ");
    QStandardItem *item = new QStandardItem(string);

    ItemModel->appendRow(item);

   // ui.view_logging->setModel(ItemModel);
    //ui.view_logging->scrollToBottom();

    int centre_x = (x1+x2)/2;
    int centre_y = (y1+y2)/2;
    ui.label_location_x_num->setText(QString::number(centre_x));
    ui.label_location_y_num->setText(QString::number(centre_y));

    ui.label_speed_x_num->setText(QString::number(1.0));

    ui.label_if_track_success->setText("success!");

    //ui.label_y_num->setText(QString::number(y1));
    //ui.label_w_num->setText(QString::number(x2));
    //ui.label_h_num->setText(QString::number(y2));

    //ui.tracking_log->setModel(ItemModel);
    //ui.tracking_log->scrollToBottom();
}

void MainWindow::slot_sub_image()
{
    if(!qnode.init()){
       ui.pbt_img->setEnabled(false);
    }
    qnode.sub_image(ui.line_img->text());
}
/*****************************************************************************
** Implementation [Slots]
*****************************************************************************/

void MainWindow::showNoMasterMessage() {
	QMessageBox msgBox;
    msgBox.setText("请确认ROS主机状态！");
	msgBox.exec();
    close();
}

/*
 * These triggers whenever the button is clicked, regardless of whether it
 * is already checked or not.
 */

void MainWindow::on_button_connect_clicked(bool check )
{
    if ( ui.checkbox_use_environment->isChecked() )
    {
        if ( !qnode.init() )
        {
			showNoMasterMessage();
        }
        else
        {
            ui.button_connect->setEnabled(false);
		}
    }
    else
    {
		if ( ! qnode.init(ui.line_edit_master->text().toStdString(),
                   ui.line_edit_host->text().toStdString()) )
        {
			showNoMasterMessage();
        }
        else
        {
			ui.button_connect->setEnabled(false);
			ui.line_edit_master->setReadOnly(true);
			ui.line_edit_host->setReadOnly(true);
			ui.line_edit_topic->setReadOnly(true);
		}
	}
}


void MainWindow::on_checkbox_use_environment_stateChanged(int state) {
	bool enabled;
	if ( state == 0 ) {
		enabled = true;
	} else {
		enabled = false;
	}
	ui.line_edit_master->setEnabled(enabled);
	ui.line_edit_host->setEnabled(enabled);
	//ui.line_edit_topic->setEnabled(enabled);
}

/*****************************************************************************
** Implemenation [Slots][manually connected]
*****************************************************************************/

/**
 * This function is signalled by the underlying model. When the model changes,
 * this will drop the cursor down to the last line in the QListview to ensure
 * the user can always see the latest log message.
 */
void MainWindow::updateLoggingView() {
        ui.view_logging->scrollToBottom();
}

/*****************************************************************************
** Implementation [Menu]
*****************************************************************************/

void MainWindow::on_actionAbout_triggered() {
    QMessageBox::about(this, tr("About ..."),tr("<h2>PACKAGE_NAME Test Program 0.10</h2><p>Copyright Yujin Robot</p><p>This package needs an about description.</p>"));
}

/*****************************************************************************
** Implementation [Configuration]
*****************************************************************************/

void MainWindow::ReadSettings() {
    QSettings settings("Qt-Ros Package", "ui_core");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
    QString master_url = settings.value("master_url",QString("http://192.168.1.24:11311/")).toString();
    QString host_url = settings.value("host_url", QString("192.168.1.24")).toString();
    //QString topic_name = settings.value("topic_name", QString("/chatter")).toString();
    ui.line_edit_master->setText(master_url);
    ui.line_edit_host->setText(host_url);
    //ui.line_edit_topic->setText(topic_name);
    bool remember = settings.value("remember_settings", false).toBool();
    ui.checkbox_remember_settings->setChecked(remember);
    bool checked = settings.value("use_environment_variables", false).toBool();
    ui.checkbox_use_environment->setChecked(checked);
    if ( checked ) {
    	ui.line_edit_master->setEnabled(false);
    	ui.line_edit_host->setEnabled(false);
    	//ui.line_edit_topic->setEnabled(false);
    }
}

void MainWindow::WriteSettings() {
    QSettings settings("Qt-Ros Package", "ui_core");
    settings.setValue("master_url",ui.line_edit_master->text());
    settings.setValue("host_url",ui.line_edit_host->text());
    //settings.setValue("topic_name",ui.line_edit_topic->text());
    settings.setValue("use_environment_variables",QVariant(ui.checkbox_use_environment->isChecked()));
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
    settings.setValue("remember_settings",QVariant(ui.checkbox_remember_settings->isChecked()));

}

void MainWindow::closeEvent(QCloseEvent *event)
{
	WriteSettings();
	QMainWindow::closeEvent(event);
}

#include <std_msgs/Int32MultiArray.h>
void MainWindow::on_pbt_img_rect_clicked()
{

    std_msgs::Int32MultiArray int32MRect;
    int32MRect.data.push_back(ui.lab_img->getX1());
    int32MRect.data.push_back(ui.lab_img->getY1());
    int32MRect.data.push_back(ui.lab_img->getX2());
    int32MRect.data.push_back(ui.lab_img->getY2());

    qnode.send_rectangle_topic(int32MRect);

    ui.pbt_img_rect->setEnabled(false);

    ui.lab_img->clear_points();
}


}  // namespace ui_core





